package com.cisdi.blog.web.admin;

import com.cisdi.blog.entity.Comment;
import com.cisdi.blog.entity.User;
import com.cisdi.blog.service.BlogService;
import com.cisdi.blog.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Random;

/**
 * @author pengyangyan
 * @version 1.0.0
 * @date 2020年03月19日 16:40:00
 */
@Controller
public class CommentController {

    @Autowired
    CommentService commentService;
    @Autowired
    BlogService blogService;
    @Value("${comment.avatar}")
    private String[] avatar;

    @RequestMapping(value = "/comments/{blogId}",method = RequestMethod.GET)
    public String commentList(@PathVariable("blogId") Long blogId, Model model){
        model.addAttribute("comments",commentService.listCommentByBlogId(blogId));
        return "blog::CommentList";
    }

    @PostMapping("/comments")
    public String post(Comment comment, HttpSession httpSession){
        Long blogId = comment.getBlog().getId();
        comment.setBlog(blogService.getBlog(blogId));
        User user = (User) httpSession.getAttribute("user");
        if (user!=null){
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
        }else {
            Random random = new Random();
            int nextInt = random.nextInt(avatar.length);
            comment.setAvatar(avatar[nextInt]);
            comment.setAdminComment(false);
        }

        commentService.saveComment(comment);
        return "redirect:/comments/"+comment.getBlog().getId();
    }

}
